package com.ruoyi.datastatistics.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.basedata.domain.TerminalsDb;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.CommonHelper;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.datastatistics.Agreement.DeGaoNettyV35;
import com.ruoyi.datastatistics.domain.createcommand.PresetCommandDataInfo;
import com.ruoyi.datastatistics.service.TerminalsDbCommandService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author TsingYu
 * @version 1.0
 * @date 2025/1/11 15:04
 */
@Service
@Slf4j
public class TerminalsDbCommandServiceImpl implements TerminalsDbCommandService {

    @Resource
    private Environment env;

    private static final String DATA_KEY = "data";
    private static final String CODE_KEY = "code";
    private static final String MSG_KEY = "msg";
    private static final int SUCCESS_CODE = 1;
    private static final int FAIL_CODE = 0;

    /**
     * 终端多参数读取命令
     *
     * @param terminalsDb data
     * @return List
     */
    @Override
    public List<PresetCommandDataInfo> sendPresetReadCommand(TerminalsDb terminalsDb, List<PresetCommandDataInfo> presetCommandDatas) throws Exception {
        String requestUrl = env.getProperty("netty-url.TerminalDbCmd-TCP.requestNetty");
        String responseUrl = env.getProperty("netty-url.TerminalDbCmd-TCP.responseNetty");
        byte[] paramsInfoBytes = DeGaoNettyV35.getTerminalParamsInfoBytes(presetCommandDatas, terminalsDb.getCommunicateAddress());
        JSONObject jsonObject = sendResult(paramsInfoBytes, terminalsDb.getImei(), 5000L, requestUrl, responseUrl, terminalsDb.getCommunicationType());
        if (Objects.equals(jsonObject.getInteger(CODE_KEY), SUCCESS_CODE)) {
            String data = jsonObject.getString(DATA_KEY);
            byte[] raw = Hex.decodeHex(data);
            byte[] dataArr = new byte[raw.length - 14];
            System.arraycopy(raw, 12, dataArr, 0, raw.length - 14);
            return DeGaoNettyV35.parseReadParam(dataArr);
        } else {
            throw new ServiceException(jsonObject.getString(MSG_KEY));
        }
    }

    @Override
    public boolean sendPresetWriteCommand(TerminalsDb terminalsDb, List<PresetCommandDataInfo> presetCommandDatas, int commandType) throws Exception {
        String requestUrl, responseUrl;
        if (commandType == 1) {
            // 预置命令
            String communicationTypeUrl = DictUtils.getDictLabel("communication_type", terminalsDb.getCommunicationType());
            requestUrl = env.getProperty("netty-url." + communicationTypeUrl + "." + "requestNetty");
            responseUrl = env.getProperty("netty-url." + communicationTypeUrl + "." + "responseNetty");
        } else {
            // 实时命令
            requestUrl = env.getProperty("netty-url.TerminalDbCmd-TCP.requestNetty");
            responseUrl = env.getProperty("netty-url.TerminalDbCmd-TCP.responseNetty");
        }
        byte[] paramsInfoBytes = DeGaoNettyV35.setTerminalParamsInfoBytes(presetCommandDatas, terminalsDb.getCommunicateAddress());
        JSONObject jsonObject = sendResult(paramsInfoBytes, terminalsDb.getImei(), 100L, requestUrl, responseUrl, terminalsDb.getCommunicationType());
        if (commandType == 1 || Objects.equals(jsonObject.getInteger(CODE_KEY), SUCCESS_CODE)) {
            return true;
        }else {
            throw new ServiceException(jsonObject.getString(MSG_KEY));
        }
    }


    private JSONObject sendResult(byte[] command, String communicateAddress, Long waitTime, String requestUrl, String responseUrl, String communicationType) throws InterruptedException {
        JSONObject jsonObject = new JSONObject();
        // 下发命令
        String requestId = CommonHelper.getDbNettyBackBody(communicateAddress, command, requestUrl, communicationType);
        System.out.println(requestId);
        if (requestId == null) {
            jsonObject.put(CODE_KEY, FAIL_CODE);
            jsonObject.put(MSG_KEY, "命令下发失败");
            log.error("命令下发失败，requestId： null ");
        } else {
            Thread.sleep(5000);
            List<String> cmdResponseBody = CommonHelper.getCmdResponseBody(communicateAddress, requestId, 0, 3, responseUrl, waitTime);
            if (cmdResponseBody.isEmpty()) {
                jsonObject.put(CODE_KEY, FAIL_CODE);
                jsonObject.put(MSG_KEY, "命令下发成功，无响应");
                log.error("命令下发成功，无响应");
            } else {
                log.info("本次命令下发返回结果：{}", cmdResponseBody);
                jsonObject.put(CODE_KEY, SUCCESS_CODE);
                jsonObject.put(DATA_KEY, cmdResponseBody.get(0));
            }
        }
        return jsonObject;
    }

}
